import 'package:flutter/material.dart';

// 保持活跃容器
class XinDongKeepAliveContainer extends StatefulWidget {
  final bool keepAlive; // 按需自动标记是否保持活跃，实现缓存
  final Widget? child; // 子组件
  final Function? initCallback;
  final Function? disposeCallback;
  final Function? deactivateCallback;

  const XinDongKeepAliveContainer({Key? key, required this.keepAlive, this.child, this.initCallback, this.disposeCallback, this.deactivateCallback})
      : super(key: key);

  @override
  State<XinDongKeepAliveContainer> createState() => _XinDongKeepAliveContainerState();
}

class _XinDongKeepAliveContainerState extends State<XinDongKeepAliveContainer> with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    super.initState();
    if (widget.initCallback != null) {
      widget.initCallback!();
    }
  }

  @override
  void dispose() {
    if (widget.disposeCallback != null) {
      widget.disposeCallback!();
    }
    super.dispose();
  }

  @override
  void deactivate() {
    super.deactivate();
    if (widget.deactivateCallback != null) {
      widget.deactivateCallback!();
    }
  }

  @override
  void didUpdateWidget(XinDongKeepAliveContainer oldWidget) {
    if (oldWidget.keepAlive != widget.keepAlive) {
      // keepAlive 状态需要更新，实现在 AutomaticKeepAliveClientMixin 中
      updateKeepAlive();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return widget.child ?? const SizedBox();
  }
}
